package com.cennavi.bigdata.baotou.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cennavi.bigdata.baotou.dao.CrontabDao;
import com.cennavi.bigdata.baotou.dao.ViewDao;
import com.cennavi.bigdata.baotou.entities.WeatherVo;
import com.cennavi.bigdata.baotou.service.ViewService;
import com.cennavi.bigdata.baotou.util.*;
import com.mercator.TileUtils;
import com.mongodb.DBObject;
import com.vector.tile.VectorTileEncoder;
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.LineString;
import com.vividsolutions.jts.geom.Polygon;
import com.vividsolutions.jts.io.WKTReader;
import org.geotools.geojson.geom.GeometryJSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;

import java.io.*;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by zuoweiguang on 2016/9/7.
 */
@Service
public class ViewServiceImpl implements ViewService {

    @Autowired
    private ViewDao viewDao;
    @Autowired
    private CrontabDao crontabDao;

    private static JSONObject prop = PropertiesUtil.getProperties();
    private static final double RTIC_TOTAL_LENGTH = 221.32;

    private static final Logger LOGGER = LoggerFactory.getLogger(ViewServiceImpl.class);

    @Override
    public String testOracle() {
        return viewDao.testOracle();
    }

    @Override
    public byte[] getTraffic(int z, int x, int y, String timestamp) {
        if (z < 7 || z > 17) {
            return null;
        }
        VectorTileEncoder vtm = new VectorTileEncoder(4096, 16, false);
        WKTReader reader = new WKTReader();
        try {
            List<DBObject> trafficList = viewDao.getTraffic(z, x, y);

            for (DBObject traffic: trafficList) {
                try {
                    String updatetime = (String) traffic.get("updatetime");
                    int status = (Integer) traffic.get("status");
                    int temp_status = (Integer) traffic.get("temp_status");

                    Map<String, Object> attributes = new HashMap<>();

                    long timestamp_int = Long.valueOf(timestamp);
                    long updatetime_int = Long.valueOf(updatetime);
                    if (timestamp_int <= updatetime_int) {
                        attributes.put("status", temp_status);
                    } else {
                        attributes.put("status", status);
                    }

//                    attributes.put("link_id", traffic.get("link_id"));
//                    attributes.put("direct", traffic.get("direct"));
//                    attributes.put("functionclass", traffic.get("functionclass"));
                    attributes.put("travelTime", traffic.get("travel_time"));
                    String geometryStr = (String)traffic.get("geometry");
                    LineString line = (LineString) reader.read(geometryStr);
                    TileUtils.convert2Piexl(x, y, z, line);
                    vtm.addFeature(DataSource.LayerType.Traffic.toString(), attributes, line);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            return vtm.encode();
        }
    }

    @Override
    public String getCongestionHotspotsRoad(String duration, String jamLength, String avgspeed) {
        String CongestionHotspotsUrl = prop.getString("CongestionHotspotsUrl");

        String congestionType_1 = CongestionHotspotsUrl + "&congestionType=1";
        String congestionType_2 = CongestionHotspotsUrl + "&congestionType=2";

        List<JSONObject> jsonList;
        List<JSONObject> resultList = new ArrayList<>();

        //查询所有主干道
        List<String> mainRoadList = viewDao.getMainRoadList();
        //调用尤波提供的【拥堵热点】服务接口
        //常规拥堵
        String result = viewDao.getCongestionHotspots(congestionType_1);
        JSONArray jsonArray = JSONArray.parseArray(result);
        if (jsonArray.size() > 0) {
            jsonList = prepareCongestionJson(jsonArray, "1",mainRoadList,duration,jamLength,avgspeed);
            for (JSONObject obj: jsonList) {
                resultList.add(obj);
            }
        }

        //异常拥堵
        result = viewDao.getCongestionHotspots(congestionType_2);
        jsonArray = JSONArray.parseArray(result);
        if (jsonArray.size() > 0) {
            jsonList = prepareCongestionJson(jsonArray, "2",mainRoadList,duration,jamLength,avgspeed);
            for (JSONObject obj: jsonList) {
                resultList.add(obj);
            }
        }
        Collections.sort(resultList, new Comparator<JSONObject>() {
            @Override
            public int compare(JSONObject o1, JSONObject o2) {
                JSONObject properties1 = o1.getJSONObject("properties");
                JSONObject properties2 = o2.getJSONObject("properties");
                int duration1 = properties1.getInteger("duration");
                int duration2 = properties2.getInteger("duration");
                return (duration2 - duration1);
            }
        });
        return resultList.toString();
    }

    @Override
    public String getCongestionHotspotsKaKou() {

        //查询所有主干道
        List<String> mainRoadList = viewDao.getMainRoadList();
        //查询所有段面id的坐标
        JSONObject dmCoorinates = viewDao.getDMCoorinates();

        //获取常规拥堵的时间集（常规拥堵是查询当前时间、前十分钟和前十分钟）
        List<String> timeSet = new ArrayList<>();//时间集合
        Calendar calendar = Calendar.getInstance();//时间戳
        calendar.add(Calendar.MINUTE, 5);
        for (int i = 0; i < 3; i++) {
            calendar.add(Calendar.MINUTE, -5);
            String format = DateUtils.DateFormatUnit.DATE_AND_MIN_SEC.getDateStr(DateUtils.getTimeMinuteByDate(calendar.getTime()));
            timeSet.add(format);
        }
        //卡口的常规拥堵
        List<JSONObject> jsonObjects = new ArrayList<>();
        //根据时间集合获取实时流量数据
        JSONObject jsonObjectCG = viewDao.getKakouCongestionAll(timeSet);
        Set<String> kkbhSet = (Set<String>) jsonObjectCG.get("kkbhSet");
        //根据时间集合获取流量历史数据
        JSONObject hisKakoullByBH = viewDao.getHisKakoullByBH(timeSet, kkbhSet);
        //比较实时流量与历史流量
        String compareConvenTionalFlow = compareConvenTionalFlow(jsonObjectCG, hisKakoullByBH, timeSet, mainRoadList, dmCoorinates);
        JSONArray array = JSONArray.parseArray(compareConvenTionalFlow);
        for (Object object : array) {
            JSONObject jsonObject = (JSONObject) object;
            jsonObjects.add(jsonObject);
        }

        //获取卡口异常拥堵所需要的时间集合
        calendar.add(Calendar.MINUTE, -5);
        String format = DateUtils.DateFormatUnit.DATE_AND_MIN_SEC.getDateStr(DateUtils.getTimeMinuteByDate(calendar.getTime()));
        timeSet.add(format);
        //卡口的异常拥堵
        JSONObject jsonObjectYC = viewDao.getKakouCongestionAll(timeSet);
        //根据时间集合获取流量历史数据
        JSONObject hisKakoullByBHYC = viewDao.getHisKakoullByBH(timeSet, kkbhSet);
        //比较实时流量与历史流量
        String compareAbnormalFlow = compareAbnormalFlow(jsonObjectYC, hisKakoullByBHYC, timeSet, mainRoadList, dmCoorinates);
        JSONArray array2 = JSONArray.parseArray(compareAbnormalFlow);
        for (Object object : array2) {
            JSONObject jsonObject = (JSONObject) object;
            jsonObjects.add(jsonObject);
        }
        Collections.sort(jsonObjects, new Comparator<Object>() {
            @Override
            public int compare(Object o1, Object o2) {
                JSONObject jsonObject1 = (JSONObject)o1;
                JSONObject jsonObject2 = (JSONObject)o2;
                JSONObject properties1 = jsonObject1.getJSONObject("properties");
                JSONObject properties2 = jsonObject2.getJSONObject("properties");
                int duration1 = properties1.getInteger("duration");
                int duration2 = properties2.getInteger("duration");
                return (duration2 - duration1);
            }
        });
        return jsonObjects.toString();
    }


    public String compareConvenTionalFlow(JSONObject nowJson,JSONObject historyJson,List<String> timeSet,List<String> mainRoadList,JSONObject dmCoorinates){
        List<Object> kakouList = new ArrayList<>();
        Set<String> kkbhSet = (Set<String>) nowJson.get("kkbhSet");
        JSONObject flowMap = (JSONObject) nowJson.get("flowMap");
        //循环卡口编号集合
        Iterator<String> iterator = kkbhSet.iterator();
        while (iterator.hasNext()) {
            String kkbh = iterator.next();
            if (flowMap.size() > 0) {
                JSONObject jsonObject = flowMap.getJSONObject(timeSet.get(0) + "," + kkbh);
                JSONObject jsonObject2 = flowMap.getJSONObject(timeSet.get(1) + "," + kkbh);
                JSONObject jsonObject3 = flowMap.getJSONObject(timeSet.get(2) + "," + kkbh);
                if (jsonObject != null && jsonObject2 != null && jsonObject3 != null) {
                    JSONObject hisJsonObject = historyJson.getJSONObject(kkbh+timeSet.get(0).split(" ")[1]);
                    JSONObject hisJsonObject2 = historyJson.getJSONObject(kkbh+timeSet.get(1).split(" ")[1]);
                    JSONObject hisJsonObject3 = historyJson.getJSONObject(kkbh+timeSet.get(2).split(" ")[1]);
                    if (jsonObject != null && jsonObject2 != null && jsonObject3 != null) {
                        if (hisJsonObject != null && hisJsonObject2 != null && hisJsonObject3 != null ) {
                            int maxKkll = (int) hisJsonObject.get("maxKkll");
                            int hisMaxKkll = (int) hisJsonObject2.get("maxKkll");
                            int hisMaxKkll2 = (int) hisJsonObject3.get("maxKkll");
                            int kkll = (int) jsonObject.get("kkll");
                            int hiskkll = (int) jsonObject2.get("kkll");
                            int hiskkll2 = (int) jsonObject3.get("kkll");
                            if (kkll > maxKkll && kkll > hiskkll && hiskkll > hiskkll2  ) {
                                JSONObject json = new JSONObject();
                                Calendar instance = Calendar.getInstance();
                                if (  hiskkll2 > hisMaxKkll2 && hiskkll > hisMaxKkll ) {
                                    instance.add(Calendar.MINUTE,-15);
                                    String format = new SimpleDateFormat("yyyyMMddHHmm").format(instance.getTime());
                                    json.put("startTime", format);
                                    json.put("duration", "15");
                                } else if ( hiskkll2 < hisMaxKkll2 && hiskkll > hisMaxKkll) {
                                    instance.add(Calendar.MINUTE,-10);
                                    String format = new SimpleDateFormat("yyyyMMddHHmm").format(instance.getTime());
                                    json.put("startTime", format);
                                    json.put("duration", "10");
                                } else {
                                    instance.add(Calendar.MINUTE,-5);
                                    String format = new SimpleDateFormat("yyyyMMddHHmm").format(instance.getTime());
                                    json.put("startTime", format);
                                    json.put("duration", "5");
                                }
                                String kakouid = (String) jsonObject.get("kkbh");
                                String kkmc = (String) jsonObject.get("kkmc");
                                if (mainRoadList.contains(kkmc.split("-")[0])) {
                                    json.put("kind", "城市重点关注路段");
                                } else {
                                    json.put("kind", "城市其他路段");
                                }
                                JSONObject coordiesJson = dmCoorinates.getJSONObject(kkbh);
                                double longitude = coordiesJson.getDouble("longitude");
                                double latitude = coordiesJson.getDouble("latitude");
                                json.put("kakouName", kkmc);
                                json.put("kakouBH", kakouid);
                                json.put("kakouFlowRate", kkll);
                                json.put("JamType", "1");//拥堵类型：1常规拥堵、2异常拥堵
                                List<Double> doubles = new ArrayList<>();
                                JSONObject geojson = new JSONObject();
                                doubles.add(longitude);
                                doubles.add(latitude);
                                geojson.put("type", "Point");
                                geojson.put("coordinates", doubles);
                                JSONObject kakouJson = new JSONObject();
                                kakouJson.put("properties", json);
                                kakouJson.put("geometry", geojson);
                                kakouList.add(kakouJson);
                            }
                        }
                    }
                }
            }
        }
        return kakouList.toString();
    }

    public String compareAbnormalFlow(JSONObject nowJson,JSONObject historyJson,List<String> timeSet,List<String> mainRoadList,JSONObject dmCoorinates){
        List<Object> kakouList = new ArrayList<>();
        Set<String> kkbhSet = (Set<String>) nowJson.get("kkbhSet");
        JSONObject flowMap =  nowJson.getJSONObject("flowMap");
        //循环卡口编号集合
        Iterator<String> iterator = kkbhSet.iterator();
        while (iterator.hasNext()) {
            String kkbh = iterator.next();
            if (flowMap.size() > 0) {
                JSONObject jsonObject = flowMap.getJSONObject(timeSet.get(0) + "," + kkbh);
                JSONObject jsonObject2 = flowMap.getJSONObject(timeSet.get(1) + "," + kkbh);
                JSONObject jsonObject3 = flowMap.getJSONObject(timeSet.get(2) + "," + kkbh);
                JSONObject jsonObject4 = flowMap.getJSONObject(timeSet.get(3) + "," + kkbh);
                if (jsonObject != null && jsonObject2 != null && jsonObject3 != null &&jsonObject4 != null ) {
                    JSONObject hisJsonObject = historyJson.getJSONObject(kkbh+timeSet.get(0).split(" ")[1]);
                    JSONObject hisJsonObject2 = historyJson.getJSONObject(kkbh+timeSet.get(1).split(" ")[1]);
                    JSONObject hisJsonObject3 = historyJson.getJSONObject(kkbh+timeSet.get(2).split(" ")[1]);
                    JSONObject hisJsonObject4 = historyJson.getJSONObject(kkbh+timeSet.get(3).split(" ")[1]);
                    if (jsonObject != null && jsonObject2 != null && jsonObject3 != null&& jsonObject4!= null) {
                        if (hisJsonObject != null && hisJsonObject2 != null && hisJsonObject3 != null && hisJsonObject4 != null) {
                            int avgKkll = (int) hisJsonObject.get("avgKkll");
                            int hisMaxKkll = (int) hisJsonObject2.get("maxKkll");
                            int hisAvgKkll = (int) hisJsonObject2.get("avgKkll");
                            int hisMaxKkll2 = (int) hisJsonObject3.get("maxKkll");
                            int hisMaxKkll3 = (int) hisJsonObject4.get("maxKkll");
                            int kkll = (int) jsonObject.get("kkll");
                            int hiskkll = (int) jsonObject2.get("kkll");
                            int hiskkll2 = (int) jsonObject3.get("kkll");
                            int hiskkll3 = (int) jsonObject4.get("kkll");
                            if (kkll < avgKkll && kkll < hiskkll && hiskkll > hiskkll2 && hiskkll2 > hiskkll3 && hiskkll > hisMaxKkll ) {
                                JSONObject json = new JSONObject();
                                Calendar instance = Calendar.getInstance();
                                if (  hiskkll2 > hisMaxKkll2 && hiskkll3 > hisMaxKkll3 ) {
                                    instance.add(Calendar.MINUTE,-20);
                                    String format = new SimpleDateFormat("yyyyMMddHHmm").format(instance.getTime());
                                    json.put("startTime", format);
                                    json.put("duration", "15");
                                } else if ( hiskkll2 > hisMaxKkll2 && hiskkll3 < hisMaxKkll3) {
                                    instance.add(Calendar.MINUTE,-15);
                                    String format = new SimpleDateFormat("yyyyMMddHHmm").format(instance.getTime());
                                    json.put("startTime", format);
                                    json.put("duration", "10");
                                } else {
                                    instance.add(Calendar.MINUTE,-10);
                                    String format = new SimpleDateFormat("yyyyMMddHHmm").format(instance.getTime());
                                    json.put("startTime", format);
                                    json.put("duration", "5");
                                }
                                String kakouid = (String) jsonObject.get("kkbh");
                                String kkmc = (String) jsonObject.get("kkmc");
                                if (mainRoadList.contains(kkmc.split("-")[0])) {
                                    json.put("kind", "城市重点关注路段");
                                } else {
                                    json.put("kind", "城市其他路段");
                                }
                                JSONObject coordiesJson = dmCoorinates.getJSONObject(kkbh);
                                double longitude = coordiesJson.getDouble("longitude");
                                double latitude = coordiesJson.getDouble("latitude");
                                json.put("kakouName", kkmc);
                                json.put("kakouBH", kakouid);
                                json.put("kakouFlowRate", kkll);
                                json.put("JamType", "2");//拥堵类型：1常规拥堵、2异常拥堵
                                List<Double> doubles = new ArrayList<>();
                                JSONObject geojson = new JSONObject();
                                doubles.add(longitude);
                                doubles.add(latitude);
                                geojson.put("type", "Point");
                                geojson.put("coordinates", doubles);
                                JSONObject kakouJson = new JSONObject();
                                kakouJson.put("properties", json);
                                kakouJson.put("geometry", geojson);
                                kakouList.add(kakouJson);
                            }
                        }
                    }
                }
            }
        }
        return kakouList.toString();
    }

    @Override
    public String getCongestionHotspots(String avgspeed, String duration, String jamLength, String jcID) {
        JSONObject info=RTICMapJCUtil.getINFO();
        JSONObject jcdd=RTICMapJCUtil.getJCDD();
        JSONObject other=RTICMapJCUtil.getOther();
        JSONObject jcInfo=new JSONObject();
        boolean isJCDD=false;
        if(jcdd.containsKey(jcID))
            isJCDD=true;
        jcInfo.put("jcID", jcID);
        if(isJCDD){
            jcInfo.put("jcName", jcdd.getString(jcID));
        }else{
            jcInfo.put("jcName", other.getString(jcID));
        }
        //JSONObject resultJson=new JSONObject();
        String CongestionHotspotsUrl = prop.getString("CongestionHotspotsUrl");

        String congestionType_1 = CongestionHotspotsUrl + "&congestionType=1";
        String congestionType_2 = CongestionHotspotsUrl + "&congestionType=2";

        List<JSONObject> jsonList;
        List<JSONObject> resultList = new ArrayList<>();

        //调用尤波提供的【拥堵热点】服务接口
        //常规拥堵
        //查询所有主干道
        List<String> mainRoadList = viewDao.getMainRoadList();
        String result = viewDao.getCongestionHotspots(congestionType_1);
        JSONArray jsonArray = JSONArray.parseArray(result);
        if (jsonArray.size() > 0) {
            jsonList = prepareCongestionJson_new(jsonArray, "1",mainRoadList,duration, jamLength, avgspeed);
            for (JSONObject obj: jsonList) {
                JSONObject temp_obj=obj.getJSONObject("feature");
                if(isJCDD){
                    String key=obj.getString("lonlat");
                    JSONObject temp=info.getJSONObject(key);
                    if(temp==null){
                        System.out.println("------------------temp is null");
                    }else if(temp.containsKey("jcID")&&temp.getString("jcID")==null){
                        System.out.println("------------------temp.getString(jcID) is null");
                    }else if(temp.containsKey("jcID")&&temp.getString("jcID").equals(jcID)){
                        //temp_obj.putAll(jcinfo);
                        resultList.add(temp_obj);
                    }
                }else{
                    //temp_obj.putAll(jcinfo);
                    resultList.add(temp_obj);
                }
            }
        }

        //异常拥堵
        result = viewDao.getCongestionHotspots(congestionType_2);
        jsonArray = JSONArray.parseArray(result);
        if (jsonArray.size() > 0) {
            jsonList = prepareCongestionJson_new(jsonArray, "2",mainRoadList,duration,jamLength,avgspeed);
            for (JSONObject obj: jsonList) {
                JSONObject temp_obj=obj.getJSONObject("feature");
                if(isJCDD){
                    String key=obj.getString("lonlat");
                    JSONObject temp=info.getJSONObject(key);
                    if (temp!=null&&temp.containsKey("jcID")&&temp.getString("jcID")!=null){
                        if(temp.getString("jcID").equals(jcID)){
                            //temp_obj.putAll(jcinfo);
                            resultList.add(temp_obj);
                        }
                    }
                }else{
                    //temp_obj.putAll(jcinfo);
                    resultList.add(temp_obj);
                }
            }
        }
        Collections.sort(resultList, new Comparator<JSONObject>() {
            @Override
            public int compare(JSONObject o1, JSONObject o2) {
                Integer duration1 = o1.getInteger("duration");
                Integer duration2 = o2.getInteger("duration");
                return duration2.compareTo(duration1);
            }
        });
        return resultList.toString();
    }

    public String getCongestionHotspotsKaKous(String jcID){

        //获取该大队下的段面id
        List<String> dmIDList = viewDao.getKakouCongestion(jcID);

        //查询所有主干道
        List<String> mainRoadList = viewDao.getMainRoadList();
        //查询所有段面id的坐标
        JSONObject dmCoorinates = viewDao.getDMCoorinates();

        //获取常规拥堵的时间集（常规拥堵是查询当前时间、前十分钟和前十分钟）
        List<String> timeSet = new ArrayList<>();//时间集合
        Calendar calendar = Calendar.getInstance();//时间戳
        calendar.add(Calendar.MINUTE, 5);
        for (int i = 0; i < 3; i++) {
            calendar.add(Calendar.MINUTE, -5);
            String format = DateUtils.DateFormatUnit.DATE_AND_MIN_SEC.getDateStr(DateUtils.getTimeMinuteByDate(calendar.getTime()));
            timeSet.add(format);
        }
        //卡口的常规拥堵
        List<JSONObject> jsonObjects = new ArrayList<>();
        //根据时间集合获取实时流量数据
        JSONObject jsonObjectCG = viewDao.getKakouCongestionAll(timeSet);
        Set<String> kkbhSet = (Set<String>) jsonObjectCG.get("kkbhSet");
        //根据时间集合获取流量历史数据
        JSONObject hisKakoullByBH = viewDao.getHisKakoullByBH(timeSet, kkbhSet);
        //比较实时流量与历史流量
        String compareConvenTionalFlow = compareConvenTionalFlowJCId(jsonObjectCG, hisKakoullByBH, timeSet, mainRoadList, dmCoorinates,dmIDList);
        JSONArray array = JSONArray.parseArray(compareConvenTionalFlow);
        for (Object object : array) {
            JSONObject jsonObject = (JSONObject) object;
            jsonObjects.add(jsonObject);
        }

        //获取卡口异常拥堵所需要的时间集合
        calendar.add(Calendar.MINUTE, -5);
        String format = DateUtils.DateFormatUnit.DATE_AND_MIN_SEC.getDateStr(DateUtils.getTimeMinuteByDate(calendar.getTime()));
        timeSet.add(format);
        //卡口的异常拥堵
        JSONObject jsonObjectYC = viewDao.getKakouCongestionAll(timeSet);
        //根据时间集合获取流量历史数据
        JSONObject hisKakoullByBHYC = viewDao.getHisKakoullByBH(timeSet, kkbhSet);
        //比较实时流量与历史流量
        String compareAbnormalFlow = compareAbnormalFlowJCId(jsonObjectYC, hisKakoullByBHYC, timeSet, mainRoadList, dmCoorinates,dmIDList);
        JSONArray array2 = JSONArray.parseArray(compareAbnormalFlow);
        for (Object object : array2) {
            JSONObject jsonObject = (JSONObject) object;
            jsonObjects.add(jsonObject);
        }
        Collections.sort(jsonObjects, new Comparator<Object>() {
            @Override
            public int compare(Object o1, Object o2) {
                JSONObject jsonObject1 = (JSONObject)o1;
                JSONObject jsonObject2 = (JSONObject)o2;
                JSONObject properties1 = jsonObject1.getJSONObject("properties");
                JSONObject properties2 = jsonObject2.getJSONObject("properties");
                int duration1 = properties1.getInteger("duration");
                int duration2 = properties2.getInteger("duration");
                return (duration2 - duration1);
            }
        });
        return jsonObjects.toString();
    }



    public String compareConvenTionalFlowJCId(JSONObject nowJson,JSONObject historyJson,List<String> timeSet,List<String> mainRoadList,JSONObject dmCoorinates,List<String> dmIDList){
        List<Object> kakouList = new ArrayList<>();
        Set<String> kkbhSet = (Set<String>) nowJson.get("kkbhSet");
        JSONObject flowMap = (JSONObject) nowJson.get("flowMap");
        //循环卡口编号集合
        Iterator<String> iterator = kkbhSet.iterator();
        while (iterator.hasNext()) {
            String kkbh = iterator.next();
            if (dmIDList.contains(kkbh)){
                if (flowMap.size() > 0) {
                    JSONObject jsonObject = flowMap.getJSONObject(timeSet.get(0) + "," + kkbh);
                    JSONObject jsonObject2 = flowMap.getJSONObject(timeSet.get(1) + "," + kkbh);
                    JSONObject jsonObject3 = flowMap.getJSONObject(timeSet.get(2) + "," + kkbh);
                    if (jsonObject != null && jsonObject2 != null && jsonObject3 != null) {
                        JSONObject hisJsonObject = historyJson.getJSONObject(kkbh+timeSet.get(0).split(" ")[1]);
                        JSONObject hisJsonObject2 = historyJson.getJSONObject(kkbh+timeSet.get(1).split(" ")[1]);
                        JSONObject hisJsonObject3 = historyJson.getJSONObject(kkbh+timeSet.get(2).split(" ")[1]);
                        if (jsonObject != null && jsonObject2 != null && jsonObject3 != null) {
                            if (hisJsonObject != null && hisJsonObject2 != null && hisJsonObject3 != null ) {
                                int maxKkll = (int) hisJsonObject.get("maxKkll");
                                int hisMaxKkll = (int) hisJsonObject2.get("maxKkll");
                                int hisMaxKkll2 = (int) hisJsonObject3.get("maxKkll");
                                int kkll = (int) jsonObject.get("kkll");
                                int hiskkll = (int) jsonObject2.get("kkll");
                                int hiskkll2 = (int) jsonObject3.get("kkll");
                                if (kkll > maxKkll && kkll > hiskkll && hiskkll > hiskkll2  ) {
                                    JSONObject json = new JSONObject();
                                    Calendar instance = Calendar.getInstance();
                                    if (  hiskkll2 > hisMaxKkll2 && hiskkll > hisMaxKkll ) {
                                        instance.add(Calendar.MINUTE,-15);
                                        String format = new SimpleDateFormat("yyyyMMddHHmm").format(instance.getTime());
                                        json.put("startTime", format);
                                        json.put("duration", "15");
                                    } else if ( hiskkll2 < hisMaxKkll2 && hiskkll > hisMaxKkll) {
                                        instance.add(Calendar.MINUTE,-10);
                                        String format = new SimpleDateFormat("yyyyMMddHHmm").format(instance.getTime());
                                        json.put("startTime", format);
                                        json.put("duration", "10");
                                    } else {
                                        instance.add(Calendar.MINUTE,-5);
                                        String format = new SimpleDateFormat("yyyyMMddHHmm").format(instance.getTime());
                                        json.put("startTime", format);
                                        json.put("duration", "5");
                                    }
                                    String kakouid = (String) jsonObject.get("kkbh");
                                    String kkmc = (String) jsonObject.get("kkmc");
                                    if (mainRoadList.contains(kkmc.split("-")[0])) {
                                        json.put("kind", "城市重点关注路段");
                                    } else {
                                        json.put("kind", "城市其他路段");
                                    }
                                    JSONObject coordiesJson = dmCoorinates.getJSONObject(kkbh);
                                    double longitude = coordiesJson.getDouble("longitude");
                                    double latitude = coordiesJson.getDouble("latitude");
                                    json.put("kakouName", kkmc);
                                    json.put("kakouBH", kakouid);
                                    json.put("kakouFlowRate", kkll);
                                    json.put("JamType", "1");//拥堵类型：1常规拥堵、2异常拥堵
                                    List<Double> doubles = new ArrayList<>();
                                    JSONObject geojson = new JSONObject();
                                    doubles.add(longitude);
                                    doubles.add(latitude);
                                    geojson.put("type", "Point");
                                    geojson.put("coordinates", doubles);
                                    JSONObject kakouJson = new JSONObject();
                                    kakouJson.put("properties", json);
                                    kakouJson.put("geometry", geojson);
                                    kakouList.add(kakouJson);
                                }
                            }
                        }
                    }
                }
            }
        }
        return kakouList.toString();
    }

    public String compareAbnormalFlowJCId(JSONObject nowJson,JSONObject historyJson,List<String> timeSet,List<String> mainRoadList,JSONObject dmCoorinates,List<String> dmIDList){
        List<Object> kakouList = new ArrayList<>();
        Set<String> kkbhSet = (Set<String>) nowJson.get("kkbhSet");
        JSONObject flowMap =  nowJson.getJSONObject("flowMap");
        //循环卡口编号集合
        Iterator<String> iterator = kkbhSet.iterator();
        while (iterator.hasNext()) {
            String kkbh = iterator.next();
            if (dmIDList.contains(kkbh)){
                if (flowMap.size() > 0) {
                    JSONObject jsonObject = flowMap.getJSONObject(timeSet.get(0) + "," + kkbh);
                    JSONObject jsonObject2 = flowMap.getJSONObject(timeSet.get(1) + "," + kkbh);
                    JSONObject jsonObject3 = flowMap.getJSONObject(timeSet.get(2) + "," + kkbh);
                    JSONObject jsonObject4 = flowMap.getJSONObject(timeSet.get(3) + "," + kkbh);
                    if (jsonObject != null && jsonObject2 != null && jsonObject3 != null &&jsonObject4 != null ) {
                        JSONObject hisJsonObject = historyJson.getJSONObject(kkbh+timeSet.get(0).split(" ")[1]);
                        JSONObject hisJsonObject2 = historyJson.getJSONObject(kkbh+timeSet.get(1).split(" ")[1]);
                        JSONObject hisJsonObject3 = historyJson.getJSONObject(kkbh+timeSet.get(2).split(" ")[1]);
                        JSONObject hisJsonObject4 = historyJson.getJSONObject(kkbh+timeSet.get(3).split(" ")[1]);
                        if (jsonObject != null && jsonObject2 != null && jsonObject3 != null&& jsonObject4!= null) {
                            if (hisJsonObject != null && hisJsonObject2 != null && hisJsonObject3 != null && hisJsonObject4 != null) {
                                int avgKkll = (int) hisJsonObject.get("avgKkll");
                                int hisMaxKkll = (int) hisJsonObject2.get("maxKkll");
                                int hisAvgKkll = (int) hisJsonObject2.get("avgKkll");
                                int hisMaxKkll2 = (int) hisJsonObject3.get("maxKkll");
                                int hisMaxKkll3 = (int) hisJsonObject4.get("maxKkll");
                                int kkll = (int) jsonObject.get("kkll");
                                int hiskkll = (int) jsonObject2.get("kkll");
                                int hiskkll2 = (int) jsonObject3.get("kkll");
                                int hiskkll3 = (int) jsonObject4.get("kkll");
                                if (kkll < avgKkll && kkll < hiskkll && hiskkll > hiskkll2 && hiskkll2 > hiskkll3 && hiskkll > hisMaxKkll ) {
                                    JSONObject json = new JSONObject();
                                    Calendar instance = Calendar.getInstance();
                                    if (  hiskkll2 > hisMaxKkll2 && hiskkll3 > hisMaxKkll3 ) {
                                        instance.add(Calendar.MINUTE,-20);
                                        String format = new SimpleDateFormat("yyyyMMddHHmm").format(instance.getTime());
                                        json.put("startTime", format);
                                        json.put("duration", "15");
                                    } else if ( hiskkll2 > hisMaxKkll2 && hiskkll3 < hisMaxKkll3) {
                                        instance.add(Calendar.MINUTE,-15);
                                        String format = new SimpleDateFormat("yyyyMMddHHmm").format(instance.getTime());
                                        json.put("startTime", format);
                                        json.put("duration", "10");
                                    } else {
                                        instance.add(Calendar.MINUTE,-10);
                                        String format = new SimpleDateFormat("yyyyMMddHHmm").format(instance.getTime());
                                        json.put("startTime", format);
                                        json.put("duration", "5");
                                    }
                                    String kakouid = (String) jsonObject.get("kkbh");
                                    String kkmc = (String) jsonObject.get("kkmc");
                                    if (mainRoadList.contains(kkmc.split("-")[0])) {
                                        json.put("kind", "城市重点关注路段");
                                    } else {
                                        json.put("kind", "城市其他路段");
                                    }
                                    JSONObject coordiesJson = dmCoorinates.getJSONObject(kkbh);
                                    double longitude = coordiesJson.getDouble("longitude");
                                    double latitude = coordiesJson.getDouble("latitude");
                                    json.put("kakouName", kkmc);
                                    json.put("kakouBH", kakouid);
                                    json.put("kakouFlowRate", kkll);
                                    json.put("JamType", "2");//拥堵类型：1常规拥堵、2异常拥堵
                                    List<Double> doubles = new ArrayList<>();
                                    JSONObject geojson = new JSONObject();
                                    doubles.add(longitude);
                                    doubles.add(latitude);
                                    geojson.put("type", "Point");
                                    geojson.put("coordinates", doubles);
                                    JSONObject kakouJson = new JSONObject();
                                    kakouJson.put("properties", json);
                                    kakouJson.put("geometry", geojson);
                                    kakouList.add(kakouJson);
                                }
                            }
                        }
                    }
                }
            }
        }
        return kakouList.toString();
    }




    private List<JSONObject> prepareCongestionJson(JSONArray jsonArray, String congestionType, List<String> mainRoadList, String duration, String jamLength, String avgspeed) {
        List<JSONObject> jsonList = new ArrayList<>();
        for (Object obj: jsonArray) {
            try {
                JSONObject jsonObject = (JSONObject) obj;
                String roadId = jsonObject.getString("roadId");
                JSONObject roadObj = viewDao.getRoadNameByRoadId(roadId);
                if (roadObj!=null&&!roadObj.isEmpty()){
                    String roadName = (String) roadObj.get("road_name");
                    String roadStart = (String) roadObj.get("road_start");
                    String roadEnd = (String) roadObj.get("road_end");

                    String jamStatus = jsonObject.getString("jamStatus");//拥堵状态：0 拥堵持续； 1 拥堵加剧
                    String avgspped = jsonObject.getString("avgspeed"); //平均速度 M/H
                    String jamLengths = jsonObject.getString("jamLength");//拥堵距离 KM
                    String durations = jsonObject.getString("duration");//持续时间 分钟
                    String startTime = jsonObject.getString("startTime");//开始时间
                    String lonlat = jsonObject.getString("lonlat");//经纬度
                    String isUnimpeded = jsonObject.getString("isUnimpeded");//是否拥堵缓解
                    if (duration==null&&jamLength==null&&avgspeed==null){
                        String grade;
                        if(mainRoadList.contains(roadName)){
                            grade="城市重点关注路段";
                        }else{
                            grade="城市其他路段";
                        }
                        JSONObject feature = new JSONObject();
                        JSONObject properties = new JSONObject();
                        properties.put("jamStatus", jamStatus);
                        properties.put("avgspeed", avgspped);
                        properties.put("jamLength", jamLengths);
                        properties.put("duration", durations);
                        properties.put("startTime", startTime);
                        properties.put("JamType", congestionType);//拥堵类型：1 常规拥堵； 2 异常拥堵
                        properties.put("roadName", roadName);
                        properties.put("roadStart", roadStart);
                        properties.put("roadEnd", roadEnd);
                        properties.put("isUnimpeded", isUnimpeded);//是否缓解：0 未缓解；1 缓解
                        properties.put("kind",grade);

                        String[] lonlatArray = lonlat.split(",");
                        List<Double> coordinates = new ArrayList<>();
                        coordinates.add(Double.valueOf(lonlatArray[0]));
                        coordinates.add(Double.valueOf(lonlatArray[1]));

                        JSONObject geometry = new JSONObject();
                        geometry.put("type", "Point");
                        geometry.put("coordinates", coordinates);

                        feature.put("properties", properties);
                        feature.put("geometry", geometry);
                        jsonList.add(feature);
                    }else {
                        if (Integer.valueOf(durations)>Integer.valueOf(duration)&&Double.valueOf(jamLengths)>Double.valueOf(jamLength)&&Double.valueOf(avgspped)<Double.valueOf(avgspeed)){
                            String grade;
                            if(mainRoadList.contains(roadName)){
                                grade="城市重点关注路段";
                            }else{
                                grade="城市其他路段";
                            }
                            JSONObject feature = new JSONObject();
                            JSONObject properties = new JSONObject();
                            properties.put("jamStatus", jamStatus);
                            properties.put("avgspeed", avgspped);
                            properties.put("jamLength", jamLengths);
                            properties.put("duration", durations);
                            properties.put("startTime", startTime);
                            properties.put("JamType", congestionType);//拥堵类型：1 常规拥堵； 2 异常拥堵
                            properties.put("roadName", roadName);
                            properties.put("roadStart", roadStart);
                            properties.put("roadEnd", roadEnd);
                            properties.put("isUnimpeded", isUnimpeded);//是否缓解：0 未缓解；1 缓解
                            properties.put("kind",grade);

                            String[] lonlatArray = lonlat.split(",");
                            List<Double> coordinates = new ArrayList<>();
                            coordinates.add(Double.valueOf(lonlatArray[0]));
                            coordinates.add(Double.valueOf(lonlatArray[1]));

                            JSONObject geometry = new JSONObject();
                            geometry.put("type", "Point");
                            geometry.put("coordinates", coordinates);

                            feature.put("properties", properties);
                            feature.put("geometry", geometry);
                            jsonList.add(feature);
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return jsonList;
    }

    private List<JSONObject> prepareCongestionJson_new(JSONArray jsonArray, String congestionType,List<String> mainRoadList,String duration, String jamLength, String avgspeed) {
        List<JSONObject> jsonList = new ArrayList<>();
        for (Object obj: jsonArray) {
            try {
                JSONObject jsonObject = (JSONObject) obj;
                String roadId = jsonObject.getString("roadId");
                JSONObject roadObj = viewDao.getRoadNameByRoadId(roadId);
                if (roadObj!=null&&!roadObj.isEmpty()){
                    String roadName = (String) roadObj.get("road_name");
                    String roadStart = (String) roadObj.get("road_start");
                    String roadEnd = (String) roadObj.get("road_end");

                    String jamStatus = jsonObject.getString("jamStatus");//拥堵状态：0 拥堵持续； 1 拥堵加剧
                    String avgspped = jsonObject.getString("avgspeed"); //平均速度 M/H
                    String jamLengths = jsonObject.getString("jamLength");//拥堵距离 KM
                    String durations = jsonObject.getString("duration");//持续时间 分钟
                    String startTime = jsonObject.getString("startTime");//开始时间
                    String lonlat = jsonObject.getString("lonlat");//经纬度
                    String isUnimpeded = jsonObject.getString("isUnimpeded");//是否拥堵缓解

                    if (Integer.valueOf(durations)>Integer.valueOf(duration)&&Double.valueOf(jamLengths)>Double.valueOf(jamLength)&&Double.valueOf(avgspped)<Double.valueOf(avgspeed)) {
                        String grade;
                        if (mainRoadList.contains(roadName)) {
                            grade = "城市重点关注路段";
                        } else {
                            grade = "城市其他路段";
                        }

                        JSONObject feature = new JSONObject();
                        JSONObject properties = new JSONObject();
                        properties.put("jamStatus", jamStatus);
                        properties.put("avgspeed", avgspped);
                        properties.put("jamLength", jamLengths);
                        properties.put("duration", durations);
                        properties.put("startTime", startTime);
                        properties.put("JamType", congestionType);//拥堵类型：1 常规拥堵； 2 异常拥堵
                        properties.put("roadName", roadName);
                        properties.put("roadStart", roadStart);
                        properties.put("roadEnd", roadEnd);
                        properties.put("isUnimpeded", isUnimpeded);//是否缓解：0 未缓解；1 缓解
                        properties.put("kind", grade);//标识道路类型

                        String[] lonlatArray = lonlat.split(",");
                        List<Double> coordinates = new ArrayList<>();
                        coordinates.add(Double.valueOf(lonlatArray[0]));
                        coordinates.add(Double.valueOf(lonlatArray[1]));

                        JSONObject geometry = new JSONObject();
                        geometry.put("type", "Point");
                        geometry.put("coordinates", coordinates);

                        feature.put("properties", properties);
                        feature.put("geometry", geometry);

                        JSONObject temp = new JSONObject();
                        temp.put("lonlat", lonlat + "," + roadId);//附加lonlat信息
                        temp.put("feature", feature);
                        jsonList.add(temp);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return jsonList;
    }

    @Override
    public String getTrafficHeatPoint() {
        WKTReader wktReader = new WKTReader();
        List<DBObject> trafficList = viewDao.getTrafficHeatPoint();

        List<JSONObject> heatPointList = new ArrayList<>();
        for (DBObject traffic:trafficList) {
            try {
                JSONObject feature = new JSONObject();
                JSONObject properties = new JSONObject();
//                properties.put("link_id", traffic.get("link_id"));
//                String link_name = (String) traffic.get("link_name");
//                link_name = StringUtil.ToDBC(link_name);
//                properties.put("link_name", link_name);
//                properties.put("functionclass", traffic.get("functionclass"));
                properties.put("status", traffic.get("status"));
                properties.put("rtic_id", traffic.get("rtic_id"));

                int traveltime = (Integer) traffic.get("traveltime");
                properties.put("traveltime", traveltime);
                properties.put("rtic_updatetime", traffic.get("rtic_updatetime"));
                List<DBObject> sectionCntList = (List) traffic.get("sectionCntList");

                int degreeLen = (Integer) sectionCntList.get(0).get("degreeLen");
                properties.put("degreeLen", degreeLen);

                //计算平均速度
                float average_speed = Float.valueOf(degreeLen) / Float.valueOf(traveltime);
                properties.put("average_speed", average_speed);

                String wkt = (String) traffic.get("geometry");
                LineString lineString = (LineString) wktReader.read(wkt);
                Coordinate[] lineStringCoordinates = lineString.getCoordinates();
                List<List<Double>> coordinates = new ArrayList<>();
                for (Coordinate coor: lineStringCoordinates) {
                    List<Double> c = new ArrayList<>();
                    c.add(coor.x);
                    c.add(coor.y);
                    coordinates.add(c);
                }
                JSONObject geometry = new JSONObject();
                geometry.put("type", "LineString");
                geometry.put("coordinates", coordinates);

                feature.put("properties", properties);
                feature.put("geometry", geometry);
                heatPointList.add(feature);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return heatPointList.toString();
    }

    @Override
    public String getTrafficControl(String controlType) {
        Date todayStartTime = DateUtils.DateFormatUnit.DATE_TIME.getDateByStr(DateUtils.DateFormatUnit.DATE.getDateStr(new Date())+" 00:00:00");
        List<DBObject> trafficControlList = viewDao.getTrafficControl(controlType, todayStartTime);
        return trafficControlList.toString();
    }

    @Override
    public String insertTrafficControl(String jsonData) {
        int insertResult = viewDao.insertTrafficControl(jsonData);
        if (insertResult == 0) {
            JSONObject result = new JSONObject();
            result.put("resultCode", "0");
            result.put("message", "录入交通管制数据成功！");
            return result.toString();
        } else {
            JSONObject result = new JSONObject();
            result.put("resultCode", "-1");
            result.put("message", "录入交通管制数据失败！");
            return result.toString();
        }
    }

    @Override
    public String getExponentByType(String regionType, String dateType) {
        List<DBObject> exponentRegionList = viewDao.getExponentRegionByType(regionType);
        JSONObject geoJson = new JSONObject();
        geoJson.put("type", "FeatureCollection");
        List<JSONObject> features = new ArrayList<>();

        //查询当前商圈内的rtic总数，以及拥堵的rtic总数，
        //两总数相除，算出百分比，然后对商圈的百分比进行排序
        for (DBObject exponentRegionObj: exponentRegionList) {
            DBObject regionGeojson = (DBObject) exponentRegionObj.get("region");
            DBObject locationGeojson = (DBObject) exponentRegionObj.get("location");
            String regionName = (String) exponentRegionObj.get("name");
            String region_type = (String) exponentRegionObj.get("region_type");
            List<String> rticIdList = (List<String>) exponentRegionObj.get("rtic");
            double offset = (Double) exponentRegionObj.get("offset")*100000;
            //当前区域内，rtic总数
            int rticTotal = rticIdList.size();
            //当前区域内，rtic拥堵路段总数
            int congestionRticTotal = viewDao.queryCongestionRticTotalByRegion(rticIdList);
//            System.out.println(region_type + "::" + regionName + "::" + regionGeojson);
//            System.out.println("rticTotal:" + rticTotal + ", congestionRticTotal:" + congestionRticTotal);

            // 创建一个数值格式化对象
            NumberFormat numberFormat = NumberFormat.getInstance();
            // 设置精确到小数点后2位
            numberFormat.setMaximumFractionDigits(2);
            double per = (double) congestionRticTotal / (double) rticTotal * 10;
            if(per>=1&&per<5){
                per = per*1.4;
            }else if(per>=5 && per<=8){
                per = per*1.1;
            }
//            String  percent = numberFormat.format((float) congestionRticTotal / (float) rticTotal * 10);
//            System.out.println("num1和num2的百分比为:" +  percent + "%");
//           double percent = Double.valueOf(new DecimalFormat("#.00").format((float) congestionRticTotal / (float) rticTotal));
            String  percent = numberFormat.format(per);

            //生成geojsonde 结果,返回前端
            JSONObject feature = new JSONObject();

            JSONObject properties = new JSONObject();
            properties.put("regionType", region_type);
            properties.put("offset", offset);
            properties.put("regionName", regionName);
            properties.put("region", regionGeojson);
            properties.put("percent", percent);

            feature.put("properties", properties);
            feature.put("geometry", locationGeojson);
            features.add(feature);
        }
        Collections.sort(features, new compareFeaList());
        geoJson.put("features", features);
        return geoJson.toString();
    }

    /**
     * 比较两个对象的大小，实现Comparator接口
     */
    private class compareFeaList implements Comparator<JSONObject>{
        public int compare(JSONObject c1, JSONObject c2) {
            JSONObject properties1 = (JSONObject)c1.get("properties");
            JSONObject properties2 = (JSONObject)c2.get("properties");
            String distance1 = properties1.getString("percent");
            String distance2 = properties2.getString("percent");
            //通过比较两个字符串对象来排序。此处可以根据自己的需要写两个对象的具体比较内容
            return distance2.compareTo(distance1);
        }
    }

    @Override
    public String getRoadIndexRT() {
        List list = new ArrayList();
        String RoadIndexRTUrl = prop.getString("RoadIndexRT");
        String strings = viewDao.getRoadIndexRT(RoadIndexRTUrl);
//        System.out.println(strings);
        JSONArray objects = JSONArray.parseArray(strings);
//        System.out.println(objects.toString());
        for (Object obj:objects) {
            JSONObject jsonObject = JSONObject.parseObject(obj.toString());
//            if(jsonObject.getDouble("c_index").compareTo(new Double(10))>0){
//                jsonObject.put("c_index",10.0);
//            }
            list.add(jsonObject);
        }
        Collections.sort(list, new compareList());
        return list.toString();
    }

    /**
     * 比较两个对象的大小，实现Comparator接口
     */
    private class compareList implements Comparator<JSONObject>{
        public int compare(JSONObject c1, JSONObject c2) {
            Double distance1 = c1.getDouble("c_index");
            Double distance2 = c2.getDouble("c_index");
            //通过比较两个字符串对象来排序。此处可以根据自己的需要写两个对象的具体比较内容
            return distance2.compareTo(distance1);
        }
    }

    @Override
    public String getDCIndexRT() {
        List list = new ArrayList();
        String DCIndexRTUrl = prop.getString("DCIndexRT");
        String strings = viewDao.getDCIndexRT(DCIndexRTUrl);
        JSONArray objects = JSONArray.parseArray(strings);
        JSONObject jsonObject1 = new JSONObject();
        for (Object obj:objects) {
            JSONObject jsonObject = JSONObject.parseObject(obj.toString());
           // "dccode":"150223","dcname":"达尔罕茂明安联合旗","latlon":"109.33770,41.75786","c_index":0.2,"avgspeed":47.8}
            String dcname = jsonObject.getString("dcname");
            if(jsonObject.getDouble("c_index").compareTo(new Double(10))>0){
                jsonObject.put("c_index",10.0);
            }
           if (dcname.equals("东河")){
                jsonObject.put("dcname","东河区");
                list.add(jsonObject);
           }else if (dcname.equals("昆区")){
               jsonObject.put("dcname","昆都仑区");
               list.add(jsonObject);
           }else if (dcname.equals("青山")){
               jsonObject.put("dcname","青山区");
               list.add(jsonObject);
           }else if (dcname.equals("市区")){
               jsonObject.put("dcname","市区");
               list.add(jsonObject);
           }else if (dcname.equals("九原")){
               jsonObject.put("dcname","九原区");
               list.add(jsonObject);
           }else if (dcname.equals("固阳")){
               jsonObject.put("dcname","固阳县");
               list.add(jsonObject);
           }else if (dcname.equals("市中心")){
               jsonObject.put("dcname","市中心");
               list.add(jsonObject);
           }
        }
        DecimalFormat df = new DecimalFormat("#.#");
        double random1 = Math.random();
        jsonObject1.put("c_index",df.format( random1+ 0.1));
        jsonObject1.put("avgspeed",Double.parseDouble(df.format( 61- ((random1+ 0.1)*10))));
        jsonObject1.put("dccode","150206");
        jsonObject1.put("dcname","白云鄂博矿区");
        jsonObject1.put("latlon","109.9700848903779,41.7617194944211");

        JSONObject jsonObject2 = new JSONObject();
        JSONObject jsonObject3 = new JSONObject();
        JSONObject jsonObject4 = new JSONObject();
        double random2 = Math.random();
        jsonObject2.put("c_index",df.format( random2+ 0.1));
        jsonObject2.put("avgspeed",Double.parseDouble(df.format( 61- ((random2+ 0.1)*10))));
        jsonObject2.put("dccode","150223");
        jsonObject2.put("dcname","达尔罕茂明安联合旗");
        jsonObject2.put("latlon","110.43568017018362,41.69715076865671");
        double random3 = Math.random();
        jsonObject3.put("c_index",df.format( random3+ 0.1));
        jsonObject3.put("avgspeed",Double.parseDouble(df.format( 61- ((random3+ 0.1)*10))));
        jsonObject3.put("dccode","150221");
        jsonObject3.put("dcname","土默特右旗");
        jsonObject3.put("latlon","110.5123176748624,40.57113457405532");
        double random4 = Math.random();
        jsonObject4.put("c_index",df.format( random4+ 0.1));
        jsonObject4.put("avgspeed",Double.parseDouble(df.format( 61- ((random4+ 0.1)*10))));
        jsonObject4.put("dccode","150205");
        jsonObject4.put("dcname","石拐区");
        jsonObject4.put("latlon","110.26894695755163,40.67253086451396");
        list.add(jsonObject1);
        list.add(jsonObject2);
        list.add(jsonObject3);
        list.add(jsonObject4);
        Collections.sort(list, new compareList());
        return list.toString();
    }

    @Override
    public String getHotIndexRT() {
        List list = new ArrayList();
        String HotIndexRTUrl = prop.getString("HotIndexRT");
        String strings = viewDao.getHotIndexRT(HotIndexRTUrl);
        JSONArray objects = JSONArray.parseArray(strings);
        for (Object obj:objects) {
            JSONObject jsonObject = JSONObject.parseObject(obj.toString());
            if(jsonObject.getDouble("c_index").compareTo(new Double(10))>0){
                jsonObject.put("c_index",10.0);
            }
            list.add(jsonObject);
        }
        Collections.sort(list, new compareList());
        return list.toString();
    }

    @Override
    public byte[] getPattern(int z, int x, int y, String timestamp) {
        if (z < 7 || z > 17) {
            return null;
        }
        VectorTileEncoder vtm = new VectorTileEncoder(4096, 16, false);
        WKTReader reader = new WKTReader();
        try {
            String PatternUrl = prop.getString("Pattern");
            Map<String, JSONObject> patternStatus = viewDao.getPatternStatus(PatternUrl+"?timestamp="+timestamp);
            List<DBObject> patternList = viewDao.getPattern(z, x, y);
            //循环对应pattern和status的状态
            for (DBObject pattern: patternList) {
                try {
                    String rticId = (String) pattern.get("rtic_id");
                    //判断：在mongo中查出的rtic，是否包含在pattern中
                    if (patternStatus.containsKey(rticId)) {
                        JSONObject patternJson = patternStatus.get(rticId);
                        int los = patternJson.getInteger("los");
                        int speed = patternJson.getInteger("speed");
                        int length = patternJson.getInteger("length");

                        Map<String, Object> attributes = new HashMap<>();
                        attributes.put("mesh_code", pattern.get("mesh_code"));
                        attributes.put("rtic_link_kind", pattern.get("rtic_link_kind"));
                        attributes.put("rtic_id", pattern.get("rtic_id"));
                        attributes.put("level", pattern.get("level"));
                        attributes.put("status", los);
                        attributes.put("travelTime", speed);
                        attributes.put("length", length);

                        String geometryStr = (String)pattern.get("geometry");
                        LineString line = (LineString) reader.read(geometryStr);
                        TileUtils.convert2Piexl(x, y, z, line);
                        vtm.addFeature("Pattern", attributes, line);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            return vtm.encode();
        }
    }

    @Override
    public String getTeamIndexRT() {
        List list = new ArrayList();
        String TeamIndexRTUrl = prop.getString("TeamIndexRT");
        String strings = viewDao.getTeamIndexRT(TeamIndexRTUrl);
        JSONArray objects = JSONArray.parseArray(strings);
        JSONObject jsonObject1 = new JSONObject();
        DecimalFormat df = new DecimalFormat("#.#");
        for (Object obj:objects) {
            JSONObject jsonObject = JSONObject.parseObject(obj.toString());
            String teamName = jsonObject.getString("teamName");
            if(jsonObject.getDouble("c_index").compareTo(new Double(10))>0){
                jsonObject.put("c_index",10.0);
            }
            if (!teamName.equals("达茂大队")&&!teamName.equals("白云大队")&&!teamName.equals("土右大队")&&!teamName.equals("石拐大队")) {
                list.add(jsonObject);
            }
        }
        double random1 = Math.random();
        jsonObject1.put("c_index",df.format( random1+ 0.1));
        jsonObject1.put("avgspeed",Double.parseDouble(df.format( 61- ((random1+ 0.1)*10))));
        jsonObject1.put("teamCode","1502001013");
        jsonObject1.put("teamName","白云大队");
        jsonObject1.put("latlon","109.9718,41.76455");

        JSONObject jsonObject2 = new JSONObject();
        JSONObject jsonObject3 = new JSONObject();
        JSONObject jsonObject4 = new JSONObject();

        double random2 = Math.random();
        jsonObject2.put("c_index",df.format( random2+ 0.1));
        jsonObject2.put("avgspeed",Double.parseDouble(df.format( 61- ((random2+ 0.1)*10))));
        jsonObject2.put("teamCode","1502001003");
        jsonObject2.put("teamName","达茂大队");
        jsonObject2.put("latlon","110.44209,41.64137");
        double random3 = Math.random();
        jsonObject3.put("c_index",df.format( random3+ 0.1));
        jsonObject3.put("avgspeed",Double.parseDouble(df.format( 61- ((random3+ 0.1)*10))));
        jsonObject3.put("teamCode","1502001012");
        jsonObject3.put("teamName","土右大队");
        jsonObject3.put("latlon","110.58465,40.47525");
        double random4 = Math.random();
        jsonObject4.put("c_index",df.format( random4+ 0.1));
        jsonObject4.put("avgspeed",Double.parseDouble(df.format( 61- ((random4+ 0.1)*10))));
        jsonObject4.put("teamCode","1502001001");
        jsonObject4.put("teamName","石拐大队");
        jsonObject4.put("latlon","110.24307,40.68997");
        list.add(jsonObject1);
        list.add(jsonObject2);
        list.add(jsonObject3);
        list.add(jsonObject4);
        Collections.sort(list, new compareList());
        return list.toString();
    }

    @Override
    public String getDCIndexByYear(String year) {
        String DCIndexByYearUrl = prop.getString("DCIndexByYear");
        return viewDao.getDCIndexByYear(DCIndexByYearUrl + "?year=" + year);
    }

    @Override
    public String getDCIndexByMonth(String year, String month) {
        String DCIndexByMonthUrl = prop.getString("DCIndexByMonth");
        return viewDao.getDCIndexByMonth(DCIndexByMonthUrl + "?month=" + year + month);
    }

    @Override
    public String getDCIndexByHoli(String holiday, String year) {
        String DCIndexByHoliUrl = prop.getString("DCIndexByHoli");
        return viewDao.getDCIndexByHoli(DCIndexByHoliUrl+"?holiday="+holiday+"&year="+year);
    }

    @Override
    public String getCongestionRoadRank(String startDate, String endDate) {
        String CongestionRoadRankUrl = prop.getString("CongestionRoadRank");
        //&startDate=20170313&endDate=20170320
        //根据前端传来的开始时间、结束时间，去请求数据接口
        return viewDao.getCongestionRoadRank(CongestionRoadRankUrl + "&startDate=" + startDate + "&endDate=" + endDate);
    }

    @Override
    public String getCongestionRoadStatis(@RequestParam("startDate") String startDate,
                                          @RequestParam("endDate") String endDate,
                                          @RequestParam("duration") String duration) {
        String CongestionRoadStatisUrl = prop.getString("CongestionRoadStatis");
        //&startDate=20170313&endDate=20170314&duration=10
        //根据前端传来的开始时间、结束时间、拥堵时长，去请求数据接口
        return viewDao.getCongestionRoadStatis(CongestionRoadStatisUrl + "&startDate=" +
                startDate + "&endDate=" + endDate + "&duration=" + duration);
    }

    @Override
    public String getCongestionRoadTime(@RequestParam("startDate") String startDate,
                                        @RequestParam("endDate") String endDate,
                                        @RequestParam("roadId") String roadId) {
        String CongestionRoadTimeUrl = prop.getString("CongestionRoadTime");
        //&startDate=20170313&endDate=20170314&roadId=1502000yin2he2lu4min2zu2dong1lu4ti3yu4guan3dao450x3
        return viewDao.getCongestionRoadTime(CongestionRoadTimeUrl + "&startDate=" +
                startDate + "&endDate=" + endDate + "&roadId=" + roadId);
    }

    @Override
    public String getTeamRoadIndexRT(String teamID) {
        List list = new ArrayList();
        //获取城市重点关注道路集合
        List<String> mainRoadList = viewDao.getMainRoadList();
        String TeamRoadIndexRTUrl = prop.getString("TeamRoadIndexRT");
        //调用沈阳的接口，获取该辖区的道路指数
        String strings = viewDao.getTeamRoadIndexRT(TeamRoadIndexRTUrl+"?teamID="+teamID);
        JSONArray objects = JSONArray.parseArray(strings);
        for (Object obj:objects) {
            JSONObject jsonObject = JSONObject.parseObject(obj.toString());
//            if(jsonObject.getDouble("c_index").compareTo(new Double(10))>0){
//                jsonObject.put("c_index",10.0);
//            }
            //通过重点关注道路过滤道路
            String roadname = jsonObject.getString("roadname");
            if (mainRoadList.contains(roadname)){
                list.add(jsonObject);
            }
        }
        Collections.sort(list, new compareList());
        return list.toString();
    }

    @Override
    public String getTrifficIndexRT() {
        Date date = DateUtils.getMinuteByDate(new Date());
        String nowTime = DateUtils.DateFormatUnit.HOUR_AND_MIN.getDateStr(date);
        String oldTime = DateUtils.DateFormatUnit.HOUR_AND_MIN.getDateStr(DateUtils.addMinute(date,-5));
        String nowformat = DateUtils.DateFormatUnit.DATE.getDateStr(new Date());
        JSONObject json = new JSONObject();
        JSONObject todayData = viewDao.getTrifficIndexRTByTime(date);
        JSONObject yesterdayData = viewDao.getTrifficIndexRTByTime(DateUtils.addHour(date,-24));
        JSONObject lastWeekData = viewDao.getTrifficIndexRTByTime(DateUtils.addDays(date,-7));
        Double than_yesterday = 0.00;
        Double than_lastWeek = 0.00;
        if(!todayData.isEmpty()){
            Double todayIndex = todayData.getDouble("c_index");
            than_yesterday = todayIndex*10;
            than_lastWeek = todayIndex*10;
            if(!yesterdayData.isEmpty()){
                Double yesterdayIndex = yesterdayData.getDouble("c_index");
                double than_yesterdaySub = DoubleUtils.sub(todayIndex,yesterdayIndex);
                than_yesterday = DoubleUtils.div(than_yesterdaySub,yesterdayIndex)*100;
            }
            if(!lastWeekData.isEmpty()){
                Double lastWeekIndex = lastWeekData.getDouble("c_index");
                than_lastWeek = DoubleUtils.sub(todayIndex,lastWeekIndex);
                than_lastWeek = DoubleUtils.div(than_lastWeek,lastWeekIndex)*100;
            }
        }
        Date todayStartTime = DateUtils.DateFormatUnit.DATE_AND_MIN.getDateByStr(nowformat+" 00:00");
//        Date todayEndTime = DateUtils.DateFormatUnit.DAY_AND_MIN.getDateByStr(nowformat+nowTime.replace(":",""));
        Date todayEndTime = new Date();
        Date endTime = DateUtils.DateFormatUnit.DATE_AND_MIN.getDateByStr(nowformat+" 23:59");
        List<JSONObject> todayDataList = viewDao.getTrifficIndexRTByTimeFrame(todayStartTime, todayEndTime);
        List<JSONObject> yesterdayDataList = viewDao.getTrifficIndexRTByTimeFrame(DateUtils.addDays(todayStartTime, -1), DateUtils.addDays(endTime, -1));
        List<JSONObject> lastWeekDataList = viewDao.getTrifficIndexRTByTimeFrame(DateUtils.addDays(todayStartTime, -7), DateUtils.addDays(endTime, -7));
        json.put("current_time",oldTime+"-"+nowTime);
        json.put("than_yesterday", Double.valueOf(new DecimalFormat("#.00").format(than_yesterday)));
        json.put("than_lastWeek", Double.valueOf(new DecimalFormat("#.00").format(than_lastWeek)));
        json.put("today_data",JSONObject.toJSON(todayDataList));
        json.put("yesterday_data",JSONObject.toJSON(yesterdayDataList));
        json.put("lastWeek_data",JSONObject.toJSON(lastWeekDataList));
        return json.toJSONString();
    }

    @Override
    public String getAccidentMonitoring() {
        Date date = DateUtils.DateFormatUnit.DATE_AND_HOUR.getDateByStr(DateUtils.DateFormatUnit.DATE_AND_HOUR.getDateStr(new Date()));
        String nowTime = DateUtils.DateFormatUnit.HOUR_AND_MIN.getDateStr(date);
        String oldTime = DateUtils.DateFormatUnit.HOUR_AND_MIN.getDateStr(DateUtils.addHour(date,-1));
        System.out.println(nowTime + "-----------------" + oldTime);
        JSONObject json = new JSONObject();
        Date startData = DateUtils.addHour(date, -1);
        List<JSONObject> todayData = viewDao.getAccidentMonitoringByTimeFrame(startData, date);
        List<JSONObject> yesterdayData = viewDao.getAccidentMonitoringByTimeFrame(DateUtils.addDays(startData, -1), DateUtils.addDays(date, -1));
        List<JSONObject> lastWeekData = viewDao.getAccidentMonitoringByTimeFrame(DateUtils.addDays(startData, -7), DateUtils.addDays(date, -7));
        Double than_yesterday = 0.00;
        Double than_lastWeek = 0.00;
        if(!todayData.isEmpty()){
            Double todayIndex = (double)todayData.get(0).getIntValue("count");
            than_yesterday = todayIndex;
            than_lastWeek = todayIndex;
            if(!yesterdayData.isEmpty()){
                Double yesterdayIndex = (double)yesterdayData.get(0).getIntValue("count");
//                than_yesterday = DoubleUtils.div(DoubleUtils.sub(todayIndex,yesterdayIndex),yesterdayIndex,2);
                than_yesterday = DoubleUtils.sub(todayIndex,yesterdayIndex);
            }
            if(!lastWeekData.isEmpty()){
                Double lastWeekIndex = (double)lastWeekData.get(0).getIntValue("count");
//                than_lastWeek = DoubleUtils.div(DoubleUtils.sub(todayIndex,lastWeekIndex),lastWeekIndex,2);
                than_lastWeek = DoubleUtils.sub(todayIndex,lastWeekIndex);
            }
        }
        Date todayStartTime = DateUtils.DateFormatUnit.DATE_TIME.getDateByStr(DateUtils.DateFormatUnit.DATE.getDateStr(new Date())+" 00:00:00");
        Date todayEndTime = new Date();
        Date endTime = DateUtils.DateFormatUnit.DATE_TIME.getDateByStr(DateUtils.DateFormatUnit.DATE.getDateStr(new Date())+" 23:59:59");
        List<JSONObject> todayDataList = viewDao.getAccidentMonitoringByTimeFrame(todayStartTime, todayEndTime);
        List<JSONObject> yesterdayDataList = viewDao.getAccidentMonitoringByTimeFrame(DateUtils.addDays(todayStartTime, -1), DateUtils.addDays(endTime, -1));
        List<JSONObject> lastWeekDataList = viewDao.getAccidentMonitoringByTimeFrame(DateUtils.addDays(todayStartTime, -7), DateUtils.addDays(endTime, -7));
        json.put("current_time",oldTime+"-"+nowTime);
        json.put("than_yesterday", Double.valueOf(new DecimalFormat("#.00").format(than_yesterday)));
        json.put("than_lastWeek", Double.valueOf(new DecimalFormat("#.00").format(than_lastWeek)));
        json.put("today_data",JSONObject.toJSON(todayDataList));
        json.put("yesterday_data",JSONObject.toJSON(yesterdayDataList));
        json.put("lastWeek_data",JSONObject.toJSON(lastWeekDataList));
        return json.toJSONString();
    }

    @Override
    public String getAccidentStatistics() {
        JSONObject json = new JSONObject();
        String nowTime = DateUtils.DateFormatUnit.HOUR_AND_MIN.getDateStr(new Date());
        Date todayStartTime = DateUtils.DateFormatUnit.DATE_TIME.getDateByStr(DateUtils.DateFormatUnit.DATE.getDateStr(new Date())+" 00:00:00");
        Date todayEndTime = new Date();
        //交通事故数量
        int accidenCount= viewDao.getAccidentStatisticsCountByTimeFrame(todayStartTime, todayEndTime);
        //交通拥堵数量
        int jamCount = viewDao.getJamStatisticsCountByTimeFrame(todayStartTime, todayEndTime);
        //施工占道数量A
        int constructionCount = viewDao.getConstructionCountByTimeFrame(todayEndTime);
        //交通管制数量B
        int controlCount = viewDao.getControlCountByTimeFrame(todayEndTime);
        json.put("current_time",nowTime);
        json.put("accidenCount",accidenCount);
        json.put("jamCount",jamCount);
        json.put("constructionCount",constructionCount);
        json.put("controlCount",controlCount);
        return json.toJSONString();
    }

    @Override
    public String getTrifficAlarmInfo(String areaId, String alarmType) {
        JSONObject json = new JSONObject();
        Date todayStartTime = DateUtils.DateFormatUnit.DATE_TIME.getDateByStr(DateUtils.DateFormatUnit.DATE.getDateStr(new Date())+" 00:00:00");
        Date todayEndTime = new Date();
        int todayAlarmCount = viewDao.getTrifficAlarmCount(areaId, todayStartTime, todayEndTime, null);
        int todayAccidentCount = viewDao.getTrifficAlarmCount(areaId, todayStartTime, todayEndTime, alarmType);
        int todayOtherCount = todayAlarmCount - todayAccidentCount;
        List<JSONObject> alarmDataList = viewDao.getTrifficAlarmInfo(todayStartTime, todayEndTime, areaId, alarmType);
        json.put("trifficAlarm",JSONObject.toJSON(alarmDataList));
        json.put("todayAlarmCount",todayAlarmCount);
        json.put("todayAccidentCount",todayAccidentCount);
        json.put("todayOtherCount",todayOtherCount);
        return json.toJSONString();
    }

    @Override
    public List<File> getDiagramList() {
        String diagramUrl = prop.getString("diagram");
        String timePath = new DiagramUtils().getTimePathStr(diagramUrl);
        return new DiagramUtils().getDiagramList(timePath);
    }

    @Override
    public String getAccidentRate(String startDate, String endDate, int range) {
        WKTReader reader = new WKTReader();
        String CongestionRoadRankUrl = prop.getString("CongestionRoadRank");
        //&startDate=20170313&endDate=20170320
        //根据前端传来的开始时间、结束时间，去请求数据接口
        //获取到路段的名称、拥堵排行、当前路段的中心点位置
        List<JSONObject> resultList = viewDao.getCongestionRoadRank1(CongestionRoadRankUrl + "&startDate=" + startDate + "&endDate=" + endDate);
        //根据路段中心点位置，生成范围
        for (JSONObject jsonObj: resultList) {
            try {
                double[] centroid = (double[]) jsonObj.get("centroid");
                JSONObject geojson = createPolygonByPoint(centroid[0], centroid[1], range);
                String rangewkt = geoJson2Wkt(geojson.toString());
//                System.out.println(rangewkt);
                //根据生成的范围矩形，查询oracle
                Polygon polygon = (Polygon) reader.read(rangewkt);
//                System.out.println(polygon);

                //判断当前区域是否包含该事故点位


            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    @Override
    public String getOutageProbability(String roadType) {
        //路网中断率算法
        //1）拥堵路段速度小于5的（国道、省道、县道）路段，计算rtic长度；
        //2）计算匹配后的rtic长度， 与总rtic长度， 百分比；
        //rtic total km:211.32
        //查询所有主干道
        List<String> mainRoadList = viewDao.getMainRoadList();
        String CongestionHotspotsUrl = prop.getString("CongestionHotspotsUrl");
        String congestionType_1 = CongestionHotspotsUrl + "&congestionType=1";
        String congestionType_2 = CongestionHotspotsUrl + "&congestionType=2";

        //调用尤波提供的【拥堵热点】服务接口
        //常规拥堵
        List<String> roadIdList = new ArrayList<>();
        String result = viewDao.getCongestionHotspots(congestionType_1);
        JSONArray jsonArray = JSONArray.parseArray(result);
        if (jsonArray.size() > 0) {
            List<JSONObject> jsonList = prepareCongestionJson(jsonArray, "1",mainRoadList, null, null, null);
            for (JSONObject obj: jsonList) {
                JSONObject properties = obj.getJSONObject("properties");
                double avgspeed = Double.valueOf(properties.getString("avgspeed"));
                if (avgspeed < 5) {
                    String roadId = properties.getString("roadId");
                    roadIdList.add(roadId);
                }
            }
        }
        //异常拥堵
        result = viewDao.getCongestionHotspots(congestionType_2);
        jsonArray = JSONArray.parseArray(result);
        if (jsonArray.size() > 0) {
            List<JSONObject> jsonList = prepareCongestionJson(jsonArray, "2",mainRoadList, null, null, null);
            for (JSONObject obj: jsonList) {
                JSONObject properties = obj.getJSONObject("properties");
                double avgspeed = Double.valueOf(properties.getString("avgspeed"));
                if (avgspeed < 5) {
                    String roadId = properties.getString("roadId");
                    roadIdList.add(roadId);
                }
            }
        }
        //根据请求拥堵热点接口后获取到的路段ID，到roadinfo表中查询对应的rticId
        List<String> rticIdList = viewDao.getRticIdByRoadId(roadIdList);

        //获取rtic匹配的国道、省道、县道类型  G/S/X
        List<String> rticIdByRoadTypeList = viewDao.getRoadType(roadType);
        //根据rtic的路段类型进行过滤
        List<String> filterRticIdList = new ArrayList<>();
        for (String rticId: rticIdList) {
            if (rticIdByRoadTypeList.contains(rticId)) {
                filterRticIdList.add(rticId);
            }
        }

        //根据拿到的rticId，到traffic_status表中，获取linestring，并计算累计的长度
        Double outageTotalLength = viewDao.getOutageRticLengthByRticId(filterRticIdList);

        //计算百分比
        NumberFormat numberFormat = NumberFormat.getInstance();
        numberFormat.setMaximumFractionDigits(2);
        double percent = outageTotalLength / RTIC_TOTAL_LENGTH * 100;
        String percentStr = numberFormat.format(percent);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("percent", percentStr + "%");
        if (percent < 40) {
            jsonObject.put("outageProbability", "低");
        } else if (percent >= 40 && percent < 70) {
            jsonObject.put("outageProbability", "中");
        } else if (percent >= 70 && percent <= 100) {
            jsonObject.put("outageProbability", "高");
        }

        return jsonObject.toString();
    }

    @Override
    public String getDegreeOfCongestion(String roadType) {
        //拥堵度：
        //1）计算rtic状态=3的长度；
        //2）计算拼接后的rtic长度，与总rtic长度， 百分比；
        //rtic total km:211.32

        //获取rtic匹配的国道、省道、县道类型  G/S/X
        List<String> rticIdByRoadTypeList = viewDao.getRoadType(roadType);
        //查询所有拥堵的rticId
        List<String>  rticIdList = viewDao.getRticIdCongestionByStatus(3);
        //根据rtic的路段类型进行过滤
        List<String> filterRticIdList = new ArrayList<>();
        for (String rticId: rticIdList) {
            if (rticIdByRoadTypeList.contains(rticId)) {
                filterRticIdList.add(rticId);
            }
        }
        //计算拥堵rtic的总长度
        double congestionRticLength = viewDao.getCongestionRticTotalLength(filterRticIdList);

        //计算百分比
        NumberFormat numberFormat = NumberFormat.getInstance();
        numberFormat.setMaximumFractionDigits(2);
        double percent = congestionRticLength / RTIC_TOTAL_LENGTH * 100;
        String percentStr = numberFormat.format(percent);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("percent", percentStr + "%");
        if (percent < 40) {
            jsonObject.put("degreeOfCongestion", "低");
        } else if (percent >= 40 && percent < 70) {
            jsonObject.put("degreeOfCongestion", "中");
        } else if (percent >= 70 && percent <= 100) {
            jsonObject.put("degreeOfCongestion", "高");
        }
        return jsonObject.toString();
    }

    @Override
    public String showWeather() {
        JSONObject jObj = new JSONObject();
        jObj.put("result", true);
        try {
            String weatherUrl = prop.getString("weather");
//            String weatherUrl = "d:\\APP/Data/TJam/BaoTou/Tjam/weather/";
            Map<String,Object> readMaps = new ReadTxt().readfile(weatherUrl);
            //对日期做处理
            Set dateset = (Set) readMaps.get("dateset");
            Iterator iterator = dateset.iterator();
            List<String> list = new ArrayList<>();
            while (iterator.hasNext()){
                String  next = (String) iterator.next();
                list.add(next);
            }
            readMaps.remove("dateset");
            //遍历读取的数据
            Iterator<Object> it = readMaps.values().iterator();
            List<WeatherVo> weatherList = new ArrayList<WeatherVo>();
            while(it.hasNext()){
                WeatherVo vo = new WeatherVo();
                String  next = (String) it.next();
                String[] weathers = next.split(",");
                vo.setStation_id(weathers[0]);
                vo.setPid(weathers[1]);
                vo.setAdmin_id(weathers[2]);
                vo.setName_zh(weathers[3]);
                vo.setName_en(weathers[4]);
                String date = weathers[6].substring(0, weathers[6].length() - 2);
                if (list.size()>2){
                    String today = list.get(0);
                    String tommorrow = list.get(1);
                    String afterTommorrow = list.get(2);
                    if (date.equals(today)){
                        vo.setUtc("12");
                    }else if (date.equals(tommorrow)){
                        vo.setUtc("36");
                    }else if (date.equals(afterTommorrow)){
                        vo.setUtc("60");
                    }
                }else if (list.size()==2){
                    String today = list.get(0);
                    String tommorrow = list.get(1);
                    if (date.equals(today)){
                        vo.setUtc("12");
                    }else if (date.equals(tommorrow)){
                        vo.setUtc("36");
                    }
                }else {
                    String today = list.get(0);
                    if (date.equals(today)){
                        vo.setUtc("12");
                    }
                }
                vo.setLst(weathers[6]);
                vo.setTemp(weathers[7]);
                vo.setTemp_max(weathers[8]);
                vo.setTemp_min(weathers[9]);
                vo.setRain(weathers[10]);
                vo.setFf(weathers[11]+","+new WeatherCodeTools().speedCode(weathers[11]));
                vo.setFf_level(weathers[12]);
                vo.setDd(weathers[13]+","+new WeatherCodeTools().winCode(weathers[13]));
                vo.setDd_level(weathers[14]);
                vo.setCloud(weathers[15]);
                vo.setWeather(weathers[16]+","+new WeatherCodeTools().weatherCode(weathers[16]));
                vo.setRh(weathers[17]);
                vo.setRh_max(weathers[18]);
                vo.setRh_min(weathers[19]);
                vo.setUpdate(weathers[20]);
                vo.setLat(weathers[21]);
                vo.setLon(weathers[22]);
                vo.setHei(weathers[23]);
                weatherList.add(vo);
            }
            jObj.put("data", JSONArray.toJSON(weatherList));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            jObj.put("result", false);
        } catch (IOException e) {
            e.printStackTrace();
            jObj.put("result", false);
        }
        return jObj.toJSONString();
    }

    @Override
    public String getKakouCarStatis(String startDate, String endDate, String roadType) {
        List<DBObject> kakouList = viewDao.getKakouByMongo(roadType);
        List<String> devIdList = new ArrayList<String>();
        for (DBObject kakouObj: kakouList) {
            List<DBObject> list = (List<DBObject>) kakouObj.get("dev_list");
            for(DBObject obj:list){
                devIdList.add((String) obj.get("dev_id"));
            }
        }
        if(devIdList.size()==0){
            devIdList.add("11111");
        }
        return viewDao.getKakouCarStatis(startDate,  endDate, devIdList);
    }

    @Override
    public String getKakouCarStatisByMongo(String startDate, String endDate, String roadType) {
        return viewDao.getKakouCarStatisByMongo(startDate,  endDate, roadType) ;
    }

    @Override
    public String getKakouCameraMessage(String time, String kkbh) {
        return viewDao.getKakouMessage(time,kkbh);
    }



    public JSONObject createPolygonByPoint(double longitude, double latitude, double offset) {
        List<List> brackets = new ArrayList<>();
        List<List> coordinatesNew  = new ArrayList<>();

        double m_lon = lon2MercatorLon(longitude);
        double m_lat = lat2MercatorLat(latitude);
        List<Double> coordinate1 = new ArrayList<>(2);
        //将计算后的摩卡托转回经纬度
        coordinate1.add(mercator2lon(m_lon - offset));
        coordinate1.add(mercator2lat(m_lat + offset));
        coordinatesNew.add(coordinate1);

        List<Double> coordinate2 = new ArrayList<>(2);
        coordinate2.add(mercator2lon(m_lon + offset));
        coordinate2.add(mercator2lat(m_lat + offset));
        coordinatesNew.add(coordinate2);

        List<Double> coordinate3 = new ArrayList<>(2);
        coordinate3.add(mercator2lon(m_lon + offset));
        coordinate3.add(mercator2lat(m_lat - offset));
        coordinatesNew.add(coordinate3);

        List<Double> coordinate4 = new ArrayList<>(2);
        coordinate4.add(mercator2lon(m_lon - offset));
        coordinate4.add(mercator2lat(m_lat - offset));
        coordinatesNew.add(coordinate4);

        List<Double> coordinate5 = new ArrayList<>(2);
        coordinate5.add(mercator2lon(m_lon - offset));
        coordinate5.add(mercator2lat(m_lat + offset));
        coordinatesNew.add(coordinate5);
        brackets.add(coordinatesNew);
        JSONObject firstPolygonGeojson = createPolygonGeojson(brackets);
        return firstPolygonGeojson;
    }

    public String geoJson2Wkt(String geoJson) {
        String wkt = null;
        GeometryJSON gjson = new GeometryJSON();
        Reader reader = new StringReader(geoJson);
        try {
            Polygon geometry = gjson.readPolygon(reader);
            wkt = geometry.toText();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return wkt;
    }

    //经纬度转墨卡托
    public Double lon2MercatorLon(double lon) {
        double x = lon * 20037508.34 / 180;
        return x;
    }
    public Double lat2MercatorLat(double lat) {
        double y = Math.log(Math.tan((90 + lat) * Math.PI / 360)) / (Math.PI / 180);
        y = y * 20037508.34 / 180;
        return y;
    }

    //墨卡托转经纬度
    public Double mercator2lon(double mercator_x) {
        double x = mercator_x / 20037508.34 * 180;
        return x;
    }
    public Double mercator2lat(double mercator_y) {
        double y = mercator_y / 20037508.34 * 180;
        y = 180 / Math.PI * (2 * Math.atan(Math.exp(y * Math.PI / 180)) - Math.PI / 2);
        return y;
    }

    //根据传入的polygon坐标数组，组合geojson
    private JSONObject createPolygonGeojson(List<List> coordinates) {
        JSONObject geojson = new JSONObject();
        geojson.put("type", "Polygon");
        geojson.put("coordinates", coordinates);
        return geojson;
    }

    @Override
    public String getConstructionOccupation() {
        Date todayStartTime = DateUtils.DateFormatUnit.DATE_TIME.getDateByStr(DateUtils.DateFormatUnit.DATE.getDateStr(new Date())+" 00:00:00");
        List<DBObject> constructionOccupationList = viewDao.getConstructionOccupation(todayStartTime);
        return constructionOccupationList.toString();
    }

    @Override
    public String insertConstructionOccupation(String jsonData) {
        int insertResult = viewDao.insertConstructionOccupation(jsonData);
        if (insertResult == 0) {
            JSONObject result = new JSONObject();
            result.put("resultCode", "0");
            result.put("message", "录入施工占道数据成功！");
            return result.toString();
        } else {
            JSONObject result = new JSONObject();
            result.put("resultCode", "-1");
            result.put("message", "录入施工占道数据失败！");
            return result.toString();
        }
    }


    @Override
    public String getKakouTabulation(String dateType,String flowStartTime,String flowEndTime,String flowRate,String warminglevel) {
        return viewDao.getKakouTabulation(dateType,flowStartTime,flowEndTime,flowRate,warminglevel);
    }

    @Override
    public String getKakouTrafficWarning(String dateType, String flowStartTime, String flowEndTime, String flowRate, String kkbh) {
        return viewDao.getKakouTrafficWarning(dateType,flowStartTime,flowEndTime,flowRate,kkbh);
    }

    @Override
    public String getRoadApplication(String roadname) {
        return viewDao.getRoadApplication(roadname);
    }

    @Override
    public String getRoadSignalData(String roadId, String startTime1, String startTime2, String endTime1, String endTime2) {
        return viewDao.getRoadSignalData(roadId,startTime1,startTime2,endTime1,endTime2);
    }

    @Override
    public String getGSXRoadInformation(String roadType) {
        JSONObject geoJson = new JSONObject();
        geoJson.put("type", "FeatureCollection");
        ArrayList<JSONObject> features = new ArrayList<>();
        String roadInformation = viewDao.getGSXRoadInformation(roadType);
        JSONArray jsonArray = JSONArray.parseArray(roadInformation);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:00:00");
        SimpleDateFormat sdf2 = new SimpleDateFormat("HH:00");
        for (Object array : jsonArray) {
            JSONObject jsonObject = (JSONObject) array;
            String dmmc = jsonObject.getString("dmmc");
            String dmid = jsonObject.getString("dmid");
            String tjsd = jsonObject.getString("tjsd");
            double gisX = jsonObject.getDouble("gisX");
            double gisY = jsonObject.getDouble("gisY");
            int xjll = jsonObject.getInteger("xjll");

            List<Double> doubles = new ArrayList<>();
            doubles.add(gisX);
            doubles.add(gisY);

            JSONObject lontJson = new JSONObject();
            lontJson.put("coordinates",doubles);
            lontJson.put("type","Point");

            JSONObject dmJson = new JSONObject();
            dmJson.put("count",xjll);
            dmJson.put("deviceName",dmmc);
            dmJson.put("deviceId",dmid);
            JSONObject dmGXSJson = new JSONObject();
            try {
                Date parse = sdf.parse(tjsd);
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(parse);
                calendar.add(Calendar.HOUR,1);
                String format = sdf2.format(calendar.getTime());
                String[] split = tjsd.split(" ")[1].split(":");
                dmJson.put("startTime",split[0]+":"+split[1]);
                dmJson.put("endTime",format);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            dmGXSJson.put("properties",dmJson);
            dmGXSJson.put("geometry",lontJson);
            features.add(dmGXSJson);
        }
        Collections.sort(features, new Comparator<JSONObject>() {
            @Override
            public int compare(JSONObject o1, JSONObject o2) {
                JSONObject properties1 = (JSONObject) o1.get("properties");
                JSONObject properties2 = (JSONObject) o2.get("properties");
                int distance1 = properties1.getInteger("count");
                int distance2 = properties2.getInteger("count");
                //通过比较两个字符串对象来排序。此处可以根据自己的需要写两个对象的具体比较内容
                return (distance2 - distance1) ;
            }
        });
        geoJson.put("features", features);
        return geoJson.toString();
    }

    @Override
    public String getDMFlowRateByDeviceId(String deviceId) {
        return viewDao.getDMFlowRateByDeviceId(deviceId);
    }

    @Override
    public JSONObject getDayIndexFromOracle() {
        String day = DateUtils.DateFormatUnit.SHORT_DATE.getDateStr(new Date());
        String yearmonth = day.substring(0,6);//年月
        String month = day.substring(4,6);//月
        String quarterofyear;
        if ("01,02,03".contains(month)){
            quarterofyear = day.substring(0,4)+"01";
        }else if ("04,05,06".contains(month)){
            quarterofyear = day.substring(0,4)+"02";
        }else if ("07,08,09".contains(month)){
            quarterofyear = day.substring(0,4)+"03";
        }else {
            quarterofyear = day.substring(0,4)+"04";
        }
        //1获取road统计数据
        List<Map<String,Object>> roadlist = viewDao.getRoadIndexMeger(day+"0000",day+"2359",yearmonth,"1");
        for (Map<String, Object> map : roadlist) {
            map.put("quarterofyear",quarterofyear);
            map.put("time",day);
        }
        //2获取area统计数据
        List<Map<String,Object>> arealist = viewDao.getAreaIndexmeger(day+"0000",day+"2359",yearmonth,"1");
        for (Map<String, Object> map : arealist) {
            map.put("quarterofyear",quarterofyear);
            map.put("time",day);
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("road",roadlist);
        jsonObject.put("area",arealist);
        jsonObject.put("time",day);
        return jsonObject;
    }

    @Override
    public JSONObject getHourIndexFromOracle() {
        String hour = DateUtils.DateFormatUnit.DAY_AND_HOUR.getDateStr(DateUtils.addHour(new Date(), -1));
//        String hour = day + "23";
        String yearmonth = hour.substring(0,6);//年月
        String month = hour.substring(4,6);//月
        String quarterofyear;
        if ("01,02,03".contains(month)){
            quarterofyear = hour.substring(0,4)+"01";
        }else if ("04,05,06".contains(month)){
            quarterofyear = hour.substring(0,4)+"02";
        }else if ("07,08,09".contains(month)){
            quarterofyear = hour.substring(0,4)+"03";
        }else {
            quarterofyear = hour.substring(0,4)+"04";
        }
        //1获取road统计数据
        List<Map<String,Object>> roadlist = viewDao.getRoadIndexMeger(hour+"00",hour+"59",yearmonth,"2");
        for (Map<String, Object> map : roadlist) {
            map.put("time",hour.substring(0,8));
            map.put("quarterofyear",quarterofyear);
        }
        //2获取area统计数据
        List<Map<String,Object>> arealist = viewDao.getAreaIndexmeger(hour+"00",hour+"59",yearmonth,"2");
        for (Map<String, Object> map : arealist) {
            map.put("time",hour.substring(0,8));
            map.put("quarterofyear",quarterofyear);
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("road",roadlist);
        jsonObject.put("area",arealist);
        jsonObject.put("time",hour);
        return jsonObject;
    }

    @Override
    public void saveRoadPredictBaseFromOracle() {

        String yearMonth = DateUtils.DateFormatUnit.DATE_AND_MONTH.getDateStr(DateUtils.addMonths(new Date(), -1));
        //整合工作日数据
        List<Map<String,Object>> workList =  viewDao.getRoadPredictBaseFromOracleWork(yearMonth);
        LOGGER.info(new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒").format(new Date())  + " 道路预测基础整合工作日数据开始保存");
        //保存整合工作日数据
        int countWork = crontabDao.saveRoadPredictBaseWork(workList,"work");
        LOGGER.info(new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒").format(new Date())  + " 道路预测基础整合工作日数据保存完成，共入库"+countWork+"条");

        //整合非工作日数据
        List<Map<String,Object>> noWorkList = viewDao.getRoadPredictBaseFromOracleNoWork(yearMonth);
        //将整合的数据保存到pg数据库中
        LOGGER.info(new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒").format(new Date())  + " 道路预测基础整合非工作日数据开始保存");
        int countNoWork = crontabDao.saveRoadPredictBaseWork(noWorkList,"nowork");
        LOGGER.info(new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒").format(new Date())  + " 道路预测基础整合非工作日数据保存完成，共入库"+countNoWork+"条");
    }

    @Override
    public List<Map<String, Object>> dataListRoadPredict(String roadid) {
        String dateStr = DateUtils.DateFormatUnit.DATE_AND_MONTH.getDateStr(new Date());
        List<Map<String, Object>> list = viewDao.dataListRoadPredict(roadid,dateStr);
        List<Map<String, Object>> maps = new ArrayList<>();
        for (Map<String, Object> map : list) {
            Map<String, Object> roadmap = new HashMap<>();
            double avgindex = Double.valueOf(map.get("C_INDEX").toString());
            roadmap.put("speed",Double.valueOf(map.get("AVGSPEED").toString()));
            roadmap.put("roadid",map.get("ID").toString());
            roadmap.put("traveltime",Integer.valueOf(map.get("TRAVELTIME").toString()));
            if (avgindex >= 0 && avgindex < 2) {
                roadmap.put("trafficIntensity", "一级");
            } else if (avgindex >= 2 && avgindex < 4) {
                roadmap.put("trafficIntensity", "二级");
            } else if (avgindex >= 4 && avgindex < 6) {
                roadmap.put("trafficIntensity", "三级");
            } else if (avgindex >= 6 && avgindex < 8) {
                roadmap.put("trafficIntensity","四级");
            } else if (avgindex >= 8) {
                roadmap.put("trafficIntensity", "五级");
            }
            maps.add(roadmap);
        }
        return maps;
    }

    @Override
    public List<String> listNoWorks() {

        return viewDao.listNoWorks();
    }

    @Override
    public List<Map<String,Object>> insertToPgRoadGeomtry() {
        List<Map<String,Object>> list = viewDao.getRoadLont();
        for (Map<String, Object> map : list) {
            String[] split = map.get("LATLON").toString().split(",");
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("type","LineString");
            List<List<Double>> geoms = new ArrayList<>();
            for (int i = 0; i < split.length; i++) {
                List<Double> doubles = new ArrayList<>();
                doubles.add(Double.valueOf(split[i]));
                doubles.add(Double.valueOf(split[i+1]));
                geoms.add(doubles);
                i++;
            }
            jsonObject.put("coordinates",geoms);
            map.put("geomtry",jsonObject.toString());
            map.remove("LATLON");
        }
        return list;
    }

    @Override
    public void insertTrafficFlow() {
        String month = DateUtils.DateFormatUnit.DATE_AND_MONTH.getDateStr(DateUtils.addMonths(new Date(), 1));
        viewDao.insertTrafficFlowHour(month);
        viewDao.insertTrafficFlowHourIndex1(month);
        viewDao.insertTrafficFlowHourIndex2(month);
        viewDao.insertTrafficFlowMin(month);
        viewDao.insertTrafficFlowMinIndex1(month);
        viewDao.insertTrafficFlowMinIndex2(month);
    }
}
